const articalDao = require('../dao/articalDao')
const jwt = require('jsonwebtoken')
const config = require('../config/config.js')

// 发表文章
exports.post = async ctx => {
  let body = ctx.request.body
  let token = ctx.request.headers["authorization"];
  let payload = jwt.verify(token,config.security.secretKey)
  body.author = payload.username
  body.status = 0
  body.pv = 0  
  let res = await articalDao.create(body)
  ctx.success('发表成功')
}

// 获取全部
exports.getAllArtical = async ctx => {
  let { p = 1,limit = 999 } = ctx.request.query
  let offset = (p - 1) * limit;
  let body = {
    offset:offset,
    limit:Number(limit)
  }
  const res = await articalDao.findAll(body);
  ctx.success('',res)
}

// 删除某条数据
exports.delArtical = async ctx => {
  let { id } = ctx.request.query
  const res = await articalDao.delById(id);
  ctx.success('删除成功')
}

// 审核通过
exports.passArtical = async ctx => {
  let { id } = ctx.request.query
  const res = await articalDao.pass(id);
  ctx.success('审核通过')
}

// 获取精选文章
exports.getMostPV = async ctx => {
  let res = await articalDao.getMostPV()
  ctx.success('',res)
}

// 获取详情
exports.getArticalDetail = async ctx => {
  let { id } = ctx.request.query
  const res = await articalDao.findById(id);
  const r = await articalDao.addPv(id)
  ctx.success('',res)
}

// 获取推荐文章
exports.getRecommend = async ctx => {
  const res = await articalDao.findRand();
  ctx.success('',res)
}